package com.jlect.swebing.renderers.gwt.client;

import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.Widget;
import com.jlect.swebing.renderers.client.ButtonRenderer;
import com.jlect.swebing.renderers.client.ClickActionEvent;
import com.jlect.swebing.renderers.client.Image;
import com.jlect.swebing.renderers.client.RendererActionListener;

/**
 * GWT based button renderer
 * @author Sergey Kozmin
 * @since 11.11.2007 20:41:51
 */
public class ButtonRendererGWTImpl extends AbstractGWTRenderer implements ButtonRenderer, ClickListener {
    private String text;
    private Image image;

    private RendererActionListener clickListener;
    private ClickActionEvent event;

    public void setText(String text) {
        this.text = text;
    }

    public void setIcon(Image image) {
        this.image = image;
    }

    public void setActionListener(RendererActionListener listener) {
        clickListener = listener;
    }

    private Button getButton() {
        return (Button) ((CompositeAttachEventProvider)getWidget()).getTargetWidget();
    }

    protected Widget provideWidget() {
        String btnHtml;
        if (text != null) {
            btnHtml = text;
        } else if (image != null) {
            btnHtml = "<img src=" + image.getUrl() + "/>";
        } else {
            throw new IllegalArgumentException("Either text or icon objects should be not null");
        }
        Button button = new Button();
        button.setHTML(btnHtml);
        button.addClickListener(this);
        return new CompositeAttachEventProvider(button);
    }

    public void onClick(Widget sender) {
        if(clickListener != null) {
            if(event == null) {
                event = new ClickActionEvent(this, 0);//todo implement modifiers
            }
            clickListener.fireActionPerformed(event);
        }
    }

    public void setEnabled(boolean enabled) {
        getButton().setEnabled(enabled);
    }
}
